<template>
	<om-addpage :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit" :showHistoryBtn="false" :saveBtnText="'确认'">
		<om-autoform ref="autoform" :initConfigData="initConfigData" :initValue="initValue"></om-autoform>
		<view class="margin-left" style="color: #337F74;">小瓯提示：</view>
		<view class="margin-left text-gray">1、“计酬处理方式”未选择时，表单将赋值岗位信息档案中配置的岗位加班计酬方式。</view>
		<view class="margin-left text-gray">2、“计酬处理方式”选择时，表单将赋值选择的加班计酬方式。</view>
		<view class="margin-left text-gray">3、当选择“班次”时，加班人员要按照班次作息时间进行考勤，否则视为无效加班！</view>
	</om-addpage>
</template>

<script>
	import {
		errorModal,
		ignoreHtml,
		getUrl,
		confirmModal,
		ptFloat,
		minusF
	} from '@/static/js/common.js';
	import {
		buildFormData,
		formValidation,
		tranferToEditors,
		changeEditor,
		setSubmitSubValue,
		configSelectData,
		hasValue,
		formShowLoading,
		getFormFields,
		formModelLoad,
		getWorkCacheKey
	} from '@/static/js/formUtil.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
	export default {
		provide() {
			return {
				formPage: this
			};
		},
		data() {
			return buildFormData({
				initValue:{
					salaryPosId:[],
					overTimeTypeId:[],
					overTimeTypeName:[],
					overTimeTypeRatio:[]
				},
				userCache: "overtimeTemplate-overtimeTemplate-user-cache",
				prevPage: "",
				zposId: "",
				instId:"",
				instName:"",
				overTimeDay: "",
				editId: "",
				x1: '',
				x2: '',
				initConfigData: [{
					key: "title0",
					editors: [{
							checkedit: null,
							editReadonly: null,
							isfull: null,
							max: "",
							min: "",
							nameField: "instName",
							required: false,
							title: "机构名称",
							type: "labelbox",
							valueField: "instName"
						},{
							checkedit: null,
							editReadonly: null,
							isfull: null,
							max: "",
							min: "",
							nameField: "overTimeDate",
							prompt: "请选择",
							required: true,
							title: "加班日期",
							type: "newdatebox",
							valueField: "overTimeDate",
							onSelect: "onSelectOverTimeDate"
						},
						{
							checkedit: null,
							editReadonly: null,
							isfull: null,
							link: "",
							linkParam: {},
							max: "",
							min: "",
							nameField: "userName",
							prompt: "请选择",
							required: true,
							title: "姓名",
							type: "multilinkbox",
							valueField: "userId",
						},
						{
							checkedit: null,
							editReadonly: null,
							isfull: null,
							data: [],
							editReadonly: true,
							nameField: "classesName",
							required: false,
							title: "班次",
							prompt: "请选择",
							type: "selectbox",
							valueField: "classesId",
							onSelect: "classesFunc"
						},
						{
							checkedit: null,
							editReadonly: null,
							isfull: null,
							max: "",
							min: "",
							nameField: "startTime",
							onSelect: "",
							prompt: "请选择",
							required: true,
							title: "开始时间",
							type: "newtimebox",
							valueField: "startTime",
							onSelect: "startTimeFunc"
						},
						{
							checkedit: null,
							editReadonly: null,
							isfull: null,
							max: "",
							min: "",
							nameField: "endTime",
							onSelect: "",
							prompt: "请选择",
							required: true,
							title: "结束时间",
							type: "newtimebox",
							valueField: "endTime",
							onSelect: "endTimeFunc"
						},
						{
							checkedit: null,
							editReadonly: null,
							isfull: null,
							max: "",
							min: "",
							nameField: "workHoursName",
							required: false,
							title: "加班工时",
							type: "labelbox",
							valueField: "workHoursCode"
						},
						{
							checkedit: null,
							data: [],
							editReadonly: null,
							isfull: null,
							max: "",
							min: "",
							nameField: "salaryHandleName",
							onSelect: "onSelectSalaryHandle",
							prompt: "请选择",
							required: false,
							title: "计酬处理方式",
							type: "selectbox",
							valueField: "salaryHandleId"
						},
						{
							checkedit: null,
							editReadonly: null,
							isfull: null,
							max: "",
							min: "",
							nameField: "ratio",
							required: false,
							title: "计酬系数",
							type: "labelbox",
							valueField: "ratio"
						},
						{
							checkedit: null,
							editReadonly: null,
							isfull: null,
							max: "",
							min: "",
							nameField: "instructions",
							prompt: "请点击输入",
							required: true,
							title: "加班事由说明",
							type: "textarea",
							valueField: "instructions"
						}
					]
				}]
			})
		},
		computed: {
			...mapState(useLoginUserStore, ['userName', 'userId'])
		},
		methods: {
			onSelectOverTimeDate(value){
				let _that = this
				_that.om.request(
					"hrPosUtil/verifyFormDate", {
						date: value,
						busCode: _that.busCode
					},
					"post"
				).then(res => {
					if (res.value) {
						errorModal(_that, '提示信息', ignoreHtml(res.value), () => {
							_that.$refs.autoform.clear("title0", "overTimeDate")
						})
					}
				})
			},
			getSalaryPos() {
				let _that = this
				_that.om.request(
					"tposition/getSalaryPos", {
						userId: _that.userId
					}
				).then(res => {
					_that.$refs.autoform.formdata.costInstId = res.value.instId
					_that.$refs.autoform.formdata.costInstName = res.value.instName
				})
			},
			onSelectSalaryHandle(item) {
				let _that = this
				_that.$refs.autoform.formdata.ratio = item.ratio
				_that.getSalaryPos()
			},
			timeFunc(q) {
				if (this.x1 > 0) {
					let qs = q.split(':');
					if (qs[1].length > 0) {
						qs[1] = Math.round(qs[1] / 10) * 10;
						if (qs[1] == 60) {
							qs[1] = '00';
							if((qs[0] * 1 +1)<10){
								qs[0] = '0'+(qs[0] * 1 + 1);
							}else{
								qs[0] = qs[0] * 1 + 1
							}
							if (qs[0] == 24) {
								qs[0] = '00';
							}
						}else if(qs[1] == 0){
							qs[1] = '00';
						}
					}
					return qs[0] + ':' + qs[1];
				} else {
					return q;
				}
			},
			verifyTime(st, et) {
				let _that = this
				_that.om.request(
					"toverTime/verifyTime", {
						date: _that.$refs.autoform.formdata.overTimeDate,
						userId: _that.$refs.autoform.formdata.userId,
						startTime: st,
						endTime: et,
						editId: _that.editId
					}
				).then(res => {
					if (res.value) {
						_that.isVerify = true
						errorModal(_that, "提示信息", ignoreHtml(res.value), () => {
							return
						})
					}else{
						_that.isVerify = false
					}
				})
			},
			endTimeFunc(e) {
				let _that = this.$refs.autoform
				let endTime = this.timeFunc(e);
				_that.formdata.endTime = endTime;
				_that.clear('title0', 'classesId')
				if (_that.formdata.startTime) {
					if (_that.formdata.startTime > _that.formdata.endTime && _that.formdata.endTime != '00:00') {
						_that.formdata.startTime = '';
						_that.formdata.workHoursCode = '';
						_that.formdata.workHoursName = '';
					} else {
						//计算加班工时
						this.workHoursFunc();
						//验证时间是否重叠
						this.verifyTimeFunc(_that.formdata.startTime, _that.formdata.endTime);
						// this.verifyTime(_that.formdata.startTime, _that.formdata.endTime)
					}
				}
			},
			startTimeFunc(e) {
				let _that = this.$refs.autoform
				let startTime = this.timeFunc(e);
				_that.formdata.startTime = startTime;
				_that.clear('title0', 'classesId')
				_that.clear('title0', 'endTime')
				if (_that.formdata.endTime) {
					if (_that.formdata.startTime > _that.formdata.endTime && _that.formdata.endTime != '00:00') {
						_that.formdata.endTime = '';
						_that.formdata.workHoursCode = '';
						_that.formdata.workHoursName = '';
					} else {
						//计算加班工时
						this.workHoursFunc();
						//验证时间是否重叠
						this.verifyTimeFunc(_that.formdata.startTime, _that.formdata.endTime);
					}
				}
			},
			verifySingleTime() {
				let _that = this.$refs.autoform
				if (_that.x2) {
					let whc = _that.formdata.workHoursCode.replace(':', '.');
					if (whc > _that.x2) {
						confirmModal(
							_that,
							'提示信息',
							'加班没有选择班次，单条加班时长超过了' + _that.x2 + '小时，加班时段可能包含休息时段，是否继续？',
							function() {},
							function() {
								_that.formdata.endTime = '';
								_that.formdata.workHoursCode = '';
								_that.formdata.workHoursName = '';
							}
						);
					}
				}
			},
			verifyTimeFunc(sT, eT) {
				let _that = this;
				if (!sT || !eT) {
					return;
				}
				_that.om
					.request('toverTime/verifyBatchConflictTime', {
						startTime: sT,
						endTime: eT == '00:00' ? '24:00' : eT,
						date:_that.$refs.autoform.formdata.overTimeDate,
						// zposId: _that.zposId,
						userIdStr: _that.$refs.autoform.formdata.userId
					})
					.then(res => {
						if (res.value) {
							errorModal(
								_that,
								'提示信息',
								ignoreHtml(res.value),
								function() {
									_that.$refs.autoform.clear('title0', 'classesId')
									_that.$refs.autoform.formdata.startTime = '';
									_that.$refs.autoform.formdata.endTime = '';
									_that.$refs.autoform.formdata.workHoursCode = '';
									_that.$refs.autoform.formdata.workHoursName = '';
								}
							)
						} else {
							this.verifySingleTime();
						}
					})
			},
			workHoursFunc(q) {
				let _that = this.$refs.autoform;
				if (!q) {
					let st = _that.formdata.startTime.replace(':', '.');
					let et = _that.formdata.endTime.replace(':', '.');
					if (_that.formdata.endTime == '00:00') {
						et = '24.00';
					}
					if (et.substring(3, 5) < st.substring(3, 5)) {
						et -= 0.4;
					}
					q = (et - st).toFixed(2) + '';
				} else {
					let q1 = q.split('.');
					q = q1[0] + '.' + parseInt(q1[1]) * 6;
				}
				q = q.replace('.', ':');
				let qs = q.split(':');
				if (qs[0] && qs[0].length == 1) {
					qs[0] = '0' + qs[0];
				}
				if (qs[1] && qs[1].length == 1) {
					qs[1] = qs[1] + '0';
				}
				q = qs[0] + ':' + qs[1];
				let workHoursName = parseInt(qs[0]) + '小时' + parseInt(qs[1]) + '分钟';
				if (qs[0] == '00') {
					workHoursName = parseInt(qs[1]) + '分钟';
				}
				if (qs[1] == '00') {
					workHoursName = parseInt(qs[0]) + '小时';
				}
				if (qs[0] == '00' && qs[1] == '00') {
					workHoursName = '0';
				}
				_that.formdata.workHoursCode = q;
				_that.formdata.workHoursName = workHoursName;
			},
			userConfirm(salaryPosId) {
				let _that = this.$refs.autoform
				if (!_that) {
					return
				}
				this.om.request("tposition/getPosInfo", {
					"posId": salaryPosId
				}).then(res => {
					_that.formdata.salaryPosId.push(salaryPosId)
					_that.formdata.overTimeTypeId.push(res.value.overTimeTypeId)
					_that.formdata.overTimeTypeName.push(res.value.overTimeTypeName)
					_that.formdata.overTimeTypeRatio.push(res.value.overTimeTypeRatio)
				})
			},
			classesFunc(e) {
				let _that = this.$refs.autoform;
				_that.formdata.classesId = e.classesId
				_that.formdata.classesName = e.classesName
				_that.om
					.request('ttimeTable/getTime', {
						classesId: _that.formdata.classesId
					})
					.then(res => {
						if (res.succeed) {
							_that.formdata.startTime = res.value.startTime;
							_that.formdata.endTime = res.value.endTime;
							//计算加班工时
							this.workHoursFunc(res.value.ratedTime);
							this.verifyTimeFunc(res.value.startTime, res.value.endTime);
						}
					});
				//验证时间是否重叠
			},
			getDatList(){
				let _that = this
				_that.om.request(
					"toverTime/getModelList",
					{
						userIds: _that.$refs.autoform.formdata.userId,
						classesId: _that.$refs.autoform.formdata.classesId,
						startTime: _that.$refs.autoform.formdata.startTime,
						endTime: _that.$refs.autoform.formdata.endTime,
						workHoursCode: _that.$refs.autoform.formdata.workHoursCode,
						salaryHandleId: _that.$refs.autoform.formdata.salaryHandleId,
						instructions: _that.$refs.autoform.formdata.instructions,
						date: _that.$refs.autoform.formdata.overTimeDate
					},
					'post'
				).then(res=>{
					if(res.succeed){
						try {
						    uni.setStorageSync('overtimeTemplateData',res.value);
							uni.navigateBack()
						} catch (e) {
						    // error
						}
					}else{
						_that.om.toast(res.msg)
					}
				})
			},
			formSubmit() {
				let _that = this
				_that.om.request(
					"toverTime/verifyBatchConflictTime",
					{
						startTime: _that.$refs.autoform.formdata.startTime,
						endTime: _that.$refs.autoform.formdata.endTime,
						date: _that.$refs.autoform.formdata.overTimeDate,
						// zposId: _that.zposId,
						userIdStr: _that.$refs.autoform.formdata.userId
					},
					'post'
				).then(res=>{
					if(res.value){
						_that.om.toast(res.value)
					}else{
						_that.getDatList()
					}
				})
			},
			initLoad(options) {
				let _that = this
				let pro1 = _that.om.request('ttimeTable/getClassesList')
				let pro2 = _that.om.request('askLeaveDict/getOverTimeList')
				Promise.all([pro1, pro2]).then(res => {
					changeEditor("title0", "classesId", "data", configSelectData(res[0], "classesId", "classesName"), _that.initConfigData)
					changeEditor("title0", "salaryHandleId", "data", configSelectData(res[1], "id", "dicname"), _that.initConfigData)
				})
					changeEditor("title0","userId",{
						link: "../../public/multiSearch/multiSearch",
						linkParam: {
							cachename: "overtimeTemplate-overtimeTemplate-user-cache",
							initload: true,
							other: JSON.stringify({
								instId: _that.instId
							}),
							searchfield: "q",
							placeholder: "请输入姓名",
							namefield: "text",
							url: "orgInstPosUserOfficial/findUserTreeListByInst",
							showAllSelectBtn: true
						},
					},null,_that.initConfigData)
				// _that.initConfigData[0].editors[1].linkParam.other = JSON.stringify({
				// 	instId: _that.instId
				// })
				
				_that.$nextTick(function() {
					_that.$refs.autoform.formdata.instName = _that.instName
				})
			}
		},
		onLoad(options) {
			let _that = this
			uni.setNavigationBarTitle({
				title: '加班模板'
			});
			_that.zposId = options.zposId
			_that.instId = options.instId
			_that.instName = options.instName
			_that.editId = options.editId
			_that.overTimeDay = options.date
			Object.assign(_that.initValue, _that.formdata)
			_that.om.request('wxOverTime/getConst').then(res => {
				if (res.succeed) {
					_that.busCode = res.value.busCode || 'HRS1204';
					_that.x1 = res.value.x1;
					_that.x2 = res.value.x2;
					_that.initLoad(options);
				}
			});
			
			if(!_that.instId){
				errorModal(_that,"提示信息","请选择机构名称。",()=>{
					uni.navigateBack({
					})
				})
			}
		},
		onShow() {
			let _that = this
			let pages = getCurrentPages()
			_that.prevPage = pages[pages.length - 2]
			if (_that.$refs.autoform) {
				uni.getStorage({
					key: _that.userCache,
					success: (res) => {
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.userId = d.map(e => e.id).join(",")
						formdata.userName = d.map(e => e.text).join(",")
						_that.$refs.autoform.changeEditor("title0","userId",{
							initSelect:d
						})
						uni.removeStorage({
							key: _that.userCache
						})
					}
				})
			}
		}
	}
</script>

<style>
</style>
